package pl.poznan.put.cs.idss.students.kingcart.core.capturer;

import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_imgproc.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;

import java.awt.Canvas;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import com.googlecode.javacv.cpp.opencv_core.IplImage;

import pl.poznan.put.cs.idss.students.kingcart.core.tracker.SimpleTracker;
import pl.poznan.put.cs.idss.students.kingcart.core.tracker.Tracker;
import pl.poznan.put.cs.idss.students.kingcart.ui.MainCanvas;

public class VideoCapturer implements Capturer, ActionListener {

	Tracker tracker;
	private MainCanvas canvas;
	private CvCapture capture = null;
	private IplImage frame = null;
	private String fileName = "";
	private Timer timer;
	private boolean track = false;
	private int fps;

	public IplImage getFrame() {
		frame = cvQueryFrame(capture);
		return frame;

	}

	public Image getImage() {

		if (getFrame() == null)
			return null;
		// show the retrieved frame in the "Video" window
		// cvShowImage("Video", frame);
		Image cam = frame.getBufferedImage();
		// output.drawImage(cam);
		// }
		return cam;

	}

	public void initCapture() {
		// load the video file to the memory
		System.out.println("Dir: " + fileName);
		this.capture = cvCreateFileCapture(fileName);

		if (capture == null) {
			throw new NullPointerException("Capture is null");
		}

		// obtain the frames per seconds of that video
		fps = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS);
		timer = new Timer(2000 / fps, this);
		timer.start();
	}

	public void start(MainCanvas canvas) {
		this.canvas = canvas;
		initCapture();

	}

	public void stop() {
		if (timer.isRunning())
			timer.stop();
	}

	public void resumeAndTrack(Tracker tracker) {
		this.tracker = tracker;
		track = true;
		if (!timer.isRunning())
			timer.start();

	}

	public void actionPerformed(ActionEvent e) {
		Image img = getImage();
		if (track) {
			IplImage trackImage = tracker.track(frame);
			canvas.drawNextFrame(trackImage.getBufferedImage());
		} else {
			canvas.drawNextFrame(img);
		}
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

}
